﻿using Dapper;
using PersonalWebsite.Core.CQRS;
using PersonalWebsite.Core.Result;

namespace PersonalWebsite.Application.Queries.Website;

public record ProjectVO 
{
    public int Id { get; init; }
    public string Name { get; init; }
    public string Desc { get; init; }
    public string Category { get; init; }
    public string Link { get; set; }
}

public record GetCategoryProjectVO
{
    public string Category { get;  set; }

    public List<ProjectVO> Projects { get;  set; }

    public List<GetCategoryProjectVO> Convert(IEnumerable<ProjectVO> projects)
    {
        if (projects == null || !projects.Any())
            return default;

        return projects.GroupBy(c => c.Category)
            .Select(c =>
            {
                return new GetCategoryProjectVO()
                {
                    Category = c.Key,
                    Projects = c.ToList()
                };
            })?.ToList();
    }
}

public record GetCategoryProjectVOQuery : IQuery<ApiResult<List<GetCategoryProjectVO>>, List<GetCategoryProjectVO>>
{
}

public class GetCategoryProjectVOQueryHandler : QueryHandler<GetCategoryProjectVOQuery, ApiResult<List<GetCategoryProjectVO>>, List<GetCategoryProjectVO>>
{
    private readonly IDBConnectionFactory dBConnectionFactory;

    public GetCategoryProjectVOQueryHandler(IDBConnectionFactory dBConnectionFactory) : base(dBConnectionFactory)
    {
        this.dBConnectionFactory = dBConnectionFactory;
    }

    public async override Task<ApiResult<List<GetCategoryProjectVO>>> Handle(GetCategoryProjectVOQuery request, CancellationToken cancellationToken)
    {
        using var dbConnection = dBConnectionFactory.GetDbConnection();
        string sql = "SELECT * FROM WS_Project";
        var data = await dbConnection.QueryAsync<ProjectVO>(sql);

        return ApiResult<List<GetCategoryProjectVO>>.Success(new GetCategoryProjectVO().Convert(data));
    }
}